package cn.boodqian.airdata;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.Logger;
import java.util.regex.*;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import com.weedong.flex.client.AMFConnection;
import com.weedong.flex.client.ServerStatusException;
import com.weedong.flex.client.ClientStatusException;
import com.weedong.flex.messaging.io.ASObject;
import com.weedong.flex.messaging.util.Base64;

public class ShanghaiAirDataProvider implements AirDataProvider {
	private String lasterror = null;
	//private String url = "http://www.semc.com.cn:9090/ssfb/messagebroker/amf";
	private String url = "http://202.136.217.188:9090/ssfb/messagebroker/amf";
	private float lockweight_pm10 = 510f;
	private float lockweight_pm25 = 510f;
	private String keystr = "superSB`";
	private String ivstr = "Super250";
	
	private final static Logger Log = Logger.getLogger(ShanghaiAirDataProvider.class .getName()); 
	
	public ShanghaiAirDataProvider() {
	}

	public AirData getAirData(int location, int hours) {
    	assert( hours > 0 );
		if(hours>AirData.MAX_HOURS) hours = AirData.MAX_HOURS;
    	
    	ArrayList<Float> hist_pm25 = new ArrayList<Float>();
    	ArrayList<Float> hist_pm10 = new ArrayList<Float>();
    	ArrayList<Float> hist_so2 = new ArrayList<Float>();
    	ArrayList<Float> hist_no2 = new ArrayList<Float>();

        for(int i=0;i<hours;i++) {
            float t = 0f;
            hist_pm25.add(t);
            hist_pm10.add(t);
            hist_so2.add(t);
            hist_no2.add(t);
        }
        
        AirData airdata= new AirData();
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.HOUR_OF_DAY, 8-cal.getTimeZone().getOffset(new Date().getTime())/1000/3600); // To GMT+8 manually...
		airdata.setTime(cal.getTime());
        airdata.addData("pm25", hist_pm25);
        airdata.addData("pm10", hist_pm10);
        airdata.addData("so2", hist_so2);
        airdata.addData("no2", hist_no2);
    	return airdata;
	}

	@SuppressWarnings("finally")
	public ArrayList<HashMap<String, String>> getLocations() {
		//Log.i("enter");

    	return null;
	}

	public String getLastError() {
		return lasterror;
	}
	
	private String DESDecode(String in) throws Exception {
		KeySpec ks = new DESKeySpec(keystr.getBytes("UTF-8"));
		SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(ks);

		// IvParameterSpec iv = new IvParameterSpec(
		//                                          Hex.decodeHex("1234567890ABCDEF".toCharArray()));
		IvParameterSpec iv = new IvParameterSpec(ivstr.getBytes("UTF-8"));
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, key, iv);

		byte[] decoded = cipher.doFinal(Base64.decode(in));
		String decode = new String(decoded, "UTF-8");
		return decode;
	}
	
	private float getData(ASObject asobj, String key) {
		float t = 0f;
		float lockweight = 0f;
		String in = asobj.get(key).toString();
		try {
			lockweight = Float.parseFloat(asobj.get("so2AQI").toString());
		} catch(Exception e) {
			e.printStackTrace();
			return 0f;
		}
		try {
			Float pm25 = Float.parseFloat(in);
			t= pm25/1000f/lockweight;
		} catch(Exception e) {
			t = 0f;
		}
		if (Float.compare(t, 0f)==0) {
			try {
				Float pm25 = Float.parseFloat(DESDecode(in));
				t= pm25/1000f/lockweight;
			} catch(Exception e) {
				t = 0f;
			}
		}
		return t;
	}
}
